import time
from datetime import datetime

from libs.db import DB


class Cache:
    def __init__(self):
        init_sql = """
                CREATE TABLE IF NOT EXISTS cache (
                    id INTEGER PRIMARY KEY,
                    key TEXT NOT NULL,
                    value TEXT NOT NULL,
                    created DATETIME NOT NULL,
                    ttl_seconds INTEGER NOT NULL
                )
                """
        DB().run_sql(init_sql)

    def get(self, key):
        """根据key获取缓存值，检查是否过期"""
        sql = "SELECT key, value, created, ttl_seconds FROM cache WHERE key = ?"
        result = DB().fetch_one(sql, (key,))

        if result:
            key, value, created, ttl_seconds = result
            created_time = datetime.strptime(created, "%Y-%m-%d %H:%M:%S")
            ttl_time = created_time.timestamp() + ttl_seconds  # 缓存的过期时间戳

            if ttl_time > time.time():
                return value  # 返回缓存值
            else:
                # 如果缓存已经过期，则删除缓存并返回None
                self.delete(key)
                return None
        else:
            return None  # 未找到缓存


    def set(self, key, value, seconds):
        self.delete(key)
        """设置缓存，存储key, value，并指定过期时间"""
        created = datetime.now().strftime("%Y-%m-%d %H:%M:%S")  # 获取当前时间
        ttl_seconds = seconds
        sql = """
                INSERT INTO cache (key, value, created, ttl_seconds)
                VALUES (?, ?, ?, ?)
                """
        DB().run_sql(sql, (key, value, created, ttl_seconds))


    def delete(self, key):
        """删除指定key的缓存"""
        sql = "DELETE FROM cache WHERE key = ?"
        DB().run_sql(sql, (key,))


    def clear(self):
        """清空缓存表"""
        sql = "DELETE FROM cache"
        DB().run_sql(sql)
